using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using T.ServiceComponent.I18N.Service;
using T.ServiceComponent.I18N.SPI;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Action.Service;
using T.FAS.Runtime.Action.SPI;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Excel.Dao;
using T.FAS.Runtime.Excel.Entity;
using T.FAS.Runtime.Excel.SPI;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.Metadata.Client;
using T.ServiceComponent.Kernel.Service;
using  T.ServiceFramework.ServiceGateway.Client;
using AppContext = T.ServiceComponent.Session.Service.AppContext;

namespace T.FAS.Runtime.Excel.Service
{
    public class ExportExecutor : IExportExecutor
    {
        private readonly ExportTaskLogic exportTaskLogic = new ExportTaskLogic();
        private int PageSize = 1000;
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name = "dataQueryID"></param>
        /// <param name = "parameters"></param>
        /// <param name = "exportDefs"></param>
        /// <param name = "exportType"></param>
        public ExportTask ExportData(ExportParam exportParam, List<ExportParameter> parameters, List<ExportDef> exportDefs)
        {
            string userName = UserUtil.GetCurrentUserName();
            string userId = UserUtil.GetCurrentUserID();
            ExportTask exportTask = new ExportTask();
            exportTask.ID = Guid.NewGuid().ToString();
            exportTask.MetaDataID = exportParam.MetaDataID;
            exportTask.CreateTime = DateTime.Now;
            exportTask.Creator = userName;
            exportTask.UserID = userId;
            exportTask.State = 0;
            exportTask.LastModifyTime = DateTime.Now;
            exportTask.LastModifier = userName;
            IMetaDataContent metadata = MetaDataClientService.GetInstance().GetMetaDataContent(exportParam.MetaDataID);
            if (metadata == null)
                throw new FasException(ExcelConstCode.ExportFailed, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Excel_879186205", "获取元数据失败:")}" + exportParam.MetaDataID);
            exportTask.Name = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            exportTaskLogic.CreateTask(exportTask);
            exportParam.SessionID = AppContext.Current.SessionID;
            var context = ContextHelper.GetContext().Clone() as DefaultContext;
#if NETSTANDARD2_1_OR_GREATER
            var cookies = GetCookies(Kernel.Service.HttpContext.Current.Request.Cookies);
            Task.Run(() =>
            {
                ContextHelper.SetContext(context.Clone() as DefaultContext);
                DateTime startTime = DateTime.Now;
                try
                {
                    IWorkbook workbook = FileUtil.GetWorkbook();
                    ISheet sheet = CreateSheet("Sheet1", exportDefs, workbook);
                    if (exportParam.Type == 1)//导出全部
                    {
                        ExportAllPage(exportParam, parameters, exportDefs, exportTask, metadata, workbook, sheet, cookies);
                    }
                    else//导出当前页 已弃用
                    {
                        ExportCurrentPage(exportParam, parameters, exportDefs, exportTask, metadata, workbook, sheet);
                    }
                    ExportFile(exportParam, exportTask, workbook);
                }
                catch (Exception e)
                {
                    LogUtil.Log(e.ToString(), "Excel");
                    exportTask.State = 2;
                    exportTask.ErrMsg = ExceptionUtil.GetExceptionMsg(e);
                }

                exportTask.FileExts = FileUtil.DefaultExcel;
                exportTask.LastModifyTime = DateTime.Now;
                exportTask.ElapsedSeconds = (exportTask.LastModifyTime - startTime).TotalSeconds;
                exportTaskLogic.UpdateTask(exportTask);
            });
#endif
            return exportTask;
        }
#if NETSTANDARD2_1_OR_GREATER
        public Dictionary<string,string> GetCookies(Microsoft.AspNetCore.Http.IRequestCookieCollection cookies)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (cookies?.Keys.Count > 0)
            {
                foreach (var item in cookies?.Keys)
                {
                    var value = cookies[item];
                    dic.Add(item, value);
                }
            }
            return dic;
        }
#endif
        /// <summary>
        /// 导出文件
        /// </summary>
        public void ExportFile(ExportParam exportParam, ExportTask exportTask, IWorkbook workbook)
        {
            byte[] byteContent;
            using (var ms = new MemoryStream())
            {
                workbook.Write(ms,false);
                ms.Flush();
                byteContent = ms.ToArray();
            }
            workbook.Close();
            exportTask.FileSize = (byteContent.Length / 1024) + "KB";
            if (!string.IsNullOrEmpty(exportParam.FileName))
                exportTask.FileName = $"{exportParam.FileName}{DateTime.Now.ToString("HHmmss")}.{FileUtil.DefaultExcel}";
            else
                exportTask.FileName = $"{exportTask.Name}.{FileUtil.DefaultExcel}";
            UploadResult uploadResult = UploadFile(exportTask.Name, Convert.ToBase64String(byteContent), exportParam.SessionID);
            if (uploadResult.Code == "000")
            {
                exportTask.State = 1;
                exportTask.FileURL = uploadResult.RelativeUrl;
                FileUtil.LoadFile(exportTask.FileURL);
            }
            else
            {
                exportTask.State = 2;
                exportTask.ErrMsg = FileTool.GetUploadMsg(uploadResult.Code);
            }
        }

        /// <summary>
        /// 上传图片到资源服务
        /// </summary>
        public UploadResult UploadFile(string fileName, string base64, string sessionID)
        {
            string[] notCodes = new string[5] { "_", "+", "&", "%", "/" };
            foreach (var notCode in notCodes)
            {
                fileName = fileName.Replace(notCode, "");
            }
            string json = $"{{Data:\"{base64}\",Name:\"{fileName}\",Extension:\"{FileUtil.DefaultExcel}\",PathId:\"141\",CustomFileName:\"FASExport-{fileName}\"}}";
            using (var content = new StringContent(json, Encoding.UTF8, "application/json"))
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    //以下为Session校验方式   
                    httpClient.DefaultRequestHeaders.Add("SessionId", "00000000-0000-0000-0000-000000000000");
                    using (HttpResponseMessage response = httpClient.PostAsync(ConfigUtil.Instance.ResourceAPIDomain + "/api/resource/UploadDoc", content).Result) //此地址为正式环境地址，可根据实际情况修改
                    {
                        response.EnsureSuccessStatusCode();
                        //返回执行结果码
                        string result = response.Content.ReadAsStringAsync().Result;
                        UploadResult uploadResult = JsonConvert.DeserializeObject<UploadResult>(result);
                        return uploadResult;
                    }
                }
            }
        }
        /// <summary>
        /// 对接通知中心
        /// </summary>
        /// <param name="exportTask"></param>
        public static void SendNotifications(ExportTask exportTask)
        {
            Dictionary<string, string> userInfos = new Dictionary<string, string>();
            List<string> userIdList = new List<string> { exportTask.UserID };
            List<string> userNameList = new List<string> { exportTask.Creator };
            Dictionary<string, object> systemNotification = new Dictionary<string, object>
            {
                { "ID", exportTask.ID },
                { "Title", exportTask.Name },
                { "Body", "<a href=\""+ ConfigUtil.Instance.ResourceAPIDomain + "/" + exportTask.FileURL +"\" download>点击下载</a>" },
                { "Category", "TWeb_SysAnnounce" },
                { "IsPublic", true },
                { "Name", exportTask.Name + "任务导出完成通知" },
                { "SendPriority", 2 },
                { "Sequence", 1 },
                { "State", 1 },
                { "ContentType",  1 },
                { "LastModifyTime", DateTime.Now.ToString() },
                { "IsPersist", 1 },
                { "ExpireTime",  DateTime.Now.AddDays(3).ToString() },
                { "IsPopUp", 4 },
                { "IsPopUpTruth", 1 },
                { "ReceiverList", userNameList },
                { "ReceiveUserList", userIdList },

            };
            List<Dictionary<string, object>> systemNotifications = new List<Dictionary<string, object>>
            {
                systemNotification
            };
            SGHttpClient httpClient = new SGHttpClient(true);
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                { "userInfos", JsonConvert.SerializeObject(userInfos) },
                { "systemNotifications", JsonConvert.SerializeObject(systemNotifications) }
            };
            httpClient.PostCurrentIDC<object>("SNC-SendNotifications-Internal", dic, 60);
        }
        /// <summary>
        /// 导出全部
        /// </summary>
        public void ExportAllPage(ExportParam exportParam, List<ExportParameter> parameters, List<ExportDef> exportDefs, ExportTask exportTask, IMetaDataContent metadata, IWorkbook workbook, ISheet sheet, Dictionary<string, string> cookies)
        {
            if (metadata is DataQuery dataQuery)
            {
                if (dataQuery.IsBigDataQuerySource())//DA 大数据
                {
                    List<ActionParameter> actionParameters = new List<ActionParameter>();
                    foreach (var item in parameters)
                    {
                        actionParameters.Add(new ActionParameter { ParameterName = item.ParameterName, ParameterValue = item.ParameterValue });
                    }
                    actionParameters.Add(new ActionParameter { ParameterName = "IsExport", ParameterValue = true });
                    List<Dictionary<string, object>> array = GetExportData(exportParam, metadata, actionParameters);
                    exportTask.RowNum = array.Count;
                    Export(workbook, sheet, exportDefs, array, 0);
                }
                else
                {
                    ExportAll(exportParam, parameters, exportDefs, exportTask, metadata, workbook, sheet);
                }
            }
            else
            {
                PagingExport(exportParam, parameters, exportDefs, exportTask, metadata, workbook, sheet, cookies);
            }
        }
        /// <summary>
        /// 导出全部
        /// </summary>
        public void ExportAll(ExportParam exportParam, List<ExportParameter> parameters, List<ExportDef> exportDefs, ExportTask exportTask, IMetaDataContent metadata, IWorkbook workbook, ISheet sheet)
        {
            List<ActionParameter> actionParameters = new List<ActionParameter>();
            foreach (var item in parameters)
            {
                if (item.ParamType == Entity.ParamType.PageIndex)
                    item.ParameterValue = 1;
                else if (item.ParamType == Entity.ParamType.PageSize)
                    item.ParameterValue = 1000000;
                actionParameters.Add(new ActionParameter { ParameterName = item.ParameterName, ParameterValue = item.ParameterValue });
            }
            List<Dictionary<string, object>> array = GetExportData(exportParam, metadata, actionParameters);
            exportTask.RowNum = array.Count;
            Export(workbook, sheet, exportDefs, array, 0);
        }
        /// <summary>
        /// 导出当前页
        /// </summary>
        private void ExportCurrentPage(ExportParam exportParam, List<ExportParameter> parameters, List<ExportDef> exportDefs, ExportTask exportTask, IMetaDataContent metadata, IWorkbook workbook, ISheet sheet)
        {
            List<ActionParameter> actionParameters = new List<ActionParameter>();
            foreach (var item in parameters)
            {
                actionParameters.Add(new ActionParameter { ParameterName = item.ParameterName, ParameterValue = item.ParameterValue });
            }
            List<Dictionary<string, object>> array = GetExportData(exportParam, metadata, actionParameters);
            exportTask.RowNum = array.Count;
            Export(workbook, sheet, exportDefs, array, 0);
        }
        /// <summary>
        /// 循环分页查询
        /// </summary>
        public void PagingExport(ExportParam exportParam, List<ExportParameter> parameters, List<ExportDef> exportDefs, ExportTask exportTask, IMetaDataContent metadata, IWorkbook workbook, ISheet sheet, Dictionary<string, string> cookies)
        {
            int pageIndex = 0;
            int count = SetPageSizeInfo(exportParam, parameters);
            while (count == PageSize)
            {
                pageIndex++;
                List<ActionParameter> actionParameters = new List<ActionParameter>();
                foreach (var item in parameters)
                {
                    switch (item.ParamType)
                    {
                        case Entity.ParamType.PageIndex:
                            item.ParameterValue = pageIndex;
                            break;
                        case Entity.ParamType.PageSize:
                            item.ParameterValue = PageSize;
                            break;
                        default:
                            break;
                    }
                    if (!string.IsNullOrEmpty(Convert.ToString(item.ParameterValue)))
                    {
                        ActionParameter param = GetValueParam(metadata, item);
                        actionParameters.Add(param);
                    }
                    else
                    {
                        actionParameters.Add(new ActionParameter { ParameterName = item.ParameterName, ParameterValue = null });
                    }
                }
                actionParameters.Add(new ActionParameter { ParameterName = "fascookies", ParameterValue = cookies });
                var temp = GetExportData(exportParam, metadata, actionParameters);
                count = temp.Count;
                Export(workbook, sheet, exportDefs, temp, PageSize * (pageIndex - 1));
            }
            exportTask.RowNum = PageSize * (pageIndex - 1) + count;
        }
        /// <summary>
        /// 处理查询参数
        /// </summary>
        public ActionParameter GetValueParam(IMetaDataContent metadata, ExportParameter item)
        {
            var param = new ActionParameter { ParameterName = item.ParameterName, ParameterValue = item.ParameterValue };
            if (item.ParameterName == "AdvancedSort" && metadata is DataQuery dataQuery)//处理排序，在原有方案排序的基础上追加按照ID排序
            {
                var dataQueryColumn = dataQuery.GetMainSourcePkColumn();
                List<Sort> sorts = JsonConvert.DeserializeObject<List<Sort>>(item.ParameterValue.ToString());
                if (sorts?.Count(t => t.SortColumn == dataQueryColumn?.Name) == 0)
                {
                    sorts.Add(new Sort { SortColumn = dataQueryColumn?.Name, SortSource = dataQueryColumn?.DataQuerySourceID, SortType = 1 });
                }
                param.ParameterValue = JsonConvert.SerializeObject(sorts);
            }

            return param;
        }

        /// <summary>
        /// 初始化分页信息
        /// </summary>
        private int SetPageSizeInfo(ExportParam exportParam, List<ExportParameter> parameters)
        {
            PageSize = 1000;
            if (exportParam.ExportPageSize > 0)
            {
                PageSize = exportParam.ExportPageSize;
            }
            int count = PageSize;
            foreach (var item in parameters)
            {
                if (item.ParameterName == "PageIndex" || item.ParameterName == "FasPageIndex")
                    item.ParamType = Entity.ParamType.PageIndex;
                else if (item.ParameterName == "PageSize" || item.ParameterName == "FasPageCount")
                    item.ParamType = Entity.ParamType.PageSize;
            }

            return count;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name = "exportParam"></param>
        /// <param name = "metadata"></param>
        /// <param name = "actionParameters"></param>
        /// <param name = "exportTask"></param>
        /// <returns></returns>
        public List<Dictionary<string, object>> GetExportData(ExportParam exportParam, IMetaDataContent metadata, List<ActionParameter> actionParameters)
        {
            List<Dictionary<string, object>> array = new List<Dictionary<string, object>>();
            TResult tResult;
            if (metadata is ActionMetaData)
                tResult = ActionExecuteService.GetInstance.Execute(metadata.MetaDataID, Action.SPI.ActionType.Action, actionParameters, false);
            else if (metadata is DataQuery)
            {
                tResult = ActionExecuteService.GetInstance.Execute(metadata.MetaDataID, Action.SPI.ActionType.DQ, actionParameters, false);
            }
            else
                throw new FasException(ExcelConstCode.ExportFailed, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Excel_1232038745", "不支持的Action类型")}");
            if (tResult is TCommonResult<TRecord> result)
            {
                foreach (var item in result.List)
                {
                    array.Add(JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(item)));
                }
            }
            else if (tResult is TCommonResult<JObject> result2)
            {
                foreach (var item in result2.List)
                {
                    array.Add(JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(item)));
                }
            }
            else
                throw new FasException(ExcelConstCode.ExportFailed, metadata.MetaDataID + $"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Excel_1922657160", "返回结果不正确")}");
            return array;
        }

        /// <summary>
        /// 创建Sheet页并添加表头
        /// </summary>
        /// <param name = "sheetName"></param>
        /// <param name = "exportDefs"></param>
        /// <param name = "workbook"></param>
        /// <returns></returns>
        public ISheet CreateSheet(string sheetName, List<ExportDef> exportDefs, IWorkbook workbook)
        {
#if NETSTANDARD2_1_OR_GREATER
            System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endif
            ISheet sheet = workbook.CreateSheet(sheetName);
            #region 属性信息
            ICellStyle headStyle = workbook.CreateCellStyle(); //表头格式
            headStyle.Alignment = HorizontalAlignment.Center;
            IFont font = workbook.CreateFont();
            font.FontHeightInPoints = 14;
            font.IsBold = true;
            headStyle.SetFont(font);
            #endregion
            #region 表头信息
            IRow headerRow = sheet.CreateRow(0);
            for (int i = 0; i < exportDefs.Count; i++)
            {
                if (string.IsNullOrEmpty(exportDefs[i].ExcelColName))
                    throw new FasException(ExcelConstCode.ExportFailed, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Excel_944481509", "导出字段名称不能为空")}");
                headerRow.CreateCell(i).SetCellValue(exportDefs[i].ExcelColName);
                headerRow.GetCell(i).CellStyle = headStyle;
                headerRow.Height = 500;
                int colWidth = Encoding.GetEncoding(936).GetBytes(exportDefs[i].ExcelColName).Length;
                sheet.SetColumnWidth(i, (colWidth + 1) * 512); //设置列宽
            }
            #endregion
            return sheet;
        }

        /// <summary>
        /// 大数据分段写入Excel
        /// </summary>
        /// <param name = "sheetName"></param>
        /// <param name = "exportDefs"></param>
        /// <param name = "array"></param>
        /// <returns></returns>
        public void Export(IWorkbook workbook, ISheet sheet, List<ExportDef> exportDefs, List<Dictionary<string, object>> array, int startRow)
        {
            #region 详细信息
            CultureInfo cultureInfo;
            Dictionary<string, ICellStyle> styleDic = new Dictionary<string, ICellStyle>();
            cultureInfo = AppContext.Current.Language == null ? new CultureInfo("zh-CN") : new CultureInfo(AppContext.Current.Language?.ID);
            var region = RegionService.Current.GetCurrentRegion();
            if (region == null)
                region = new Region { Configs = new Dictionary<string, string>() };
            for (int i = 0; i < array.Count; i++)
            {
                IRow dataRow = sheet.CreateRow(startRow + i + 1);
                Dictionary<string, object> record = array[i];
                for (int j = 0; j < exportDefs.Count; j++)
                {
                    ICell newCell = dataRow.CreateCell(j);
                    if (!record.ContainsKey(exportDefs[j].ColName))
                        throw new FasException(ExcelConstCode.ExportFailed, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Excel_418686556", "查询结果不包含")}" + exportDefs[j].ColName);
                    object objValue = record[exportDefs[j].ColName];
                    if (objValue == null)
                    {
                        objValue = "";
                    }
                    ExportFormat exportFormat = exportDefs[j].Format;
                    ICellStyle cellStyle;
                    if (i == 0)
                    {
                        cellStyle = workbook.CreateCellStyle(); //日期格式
                        cellStyle.VerticalAlignment = VerticalAlignment.Center;
                        styleDic[exportDefs[j].ColName] = cellStyle;
                    }
                    else
                    {
                        cellStyle = styleDic[exportDefs[j].ColName];
                    }
                    IDataFormat format = workbook.CreateDataFormat();
                    if (!string.IsNullOrEmpty(exportFormat?.FormatType))
                    {
                        SetProperty(cultureInfo, newCell, Convert.ToString(objValue), exportFormat, cellStyle, format);
                    }
                    else if (exportDefs[j].Mapping?.Count > 0)
                    {
                        SetProperty(exportDefs[j], newCell, objValue);
                    }
                    else if (!string.IsNullOrEmpty(exportDefs[j].DataType))
                    {
                        SetProperty(exportDefs[j], region, newCell, Convert.ToString(objValue), cellStyle, format);
                    }
                    else
                    {
                        exportDefs[j].DataType = objValue.GetType().Name;
                        SetProperty(exportDefs[j], region, newCell, Convert.ToString(objValue), cellStyle, format);
                    }
                }
            }
            #endregion
        }
        /// <summary>
        /// 根据映射导出到Excel
        /// </summary>
        public void SetProperty(ExportDef exportDef, ICell newCell, object objValue)
        {
            string val = Convert.ToString(objValue);
            if (objValue.GetType().Name == "Boolean")
                val = val.ToLower();
            ExportMap exportMap = exportDef.Mapping.FirstOrDefault(t => t.val == val);
            if (!string.IsNullOrEmpty(exportMap?.text))
                newCell.SetCellValue(exportMap.text);
            else
                newCell.SetCellValue(val);
        }
        /// <summary>
        /// 根据格式化导出到Excel
        /// </summary>
        public void SetProperty(CultureInfo cultureInfo, ICell newCell, string val, ExportFormat exportFormat, ICellStyle cellStyle, IDataFormat format)
        {
            switch (exportFormat.FormatType)
            {
                case "DateTime":
                    DateTime dateTime;
                    bool parseSuccess = DateTime.TryParse(val, out dateTime);
                    if (parseSuccess)
                    {
                        newCell.SetCellValue(dateTime.ToString(exportFormat.DateFormat));
                    }
                    else
                        newCell.SetCellValue(val);
                    break;
                case "Currency":
                case "Number":
                case "Percent":
                    double value;
                    double.TryParse(val, out value);
                    newCell.SetCellValue(value);
                    string decimalDigit = new string('0', exportFormat.DecimalDigit);
                    string currencySymbol = exportFormat.CurrencySymbol;
                    if (currencySymbol == "auto")
                    {
                        var mainRegion = RegionService.Current.GetMainRegion();
                        if (mainRegion != null)
                            currencySymbol = mainRegion.CurrencySymbol;
                        else
                            currencySymbol = "￥";
                    }
                    if (exportFormat.ThousandsSeparator)
                        cellStyle.DataFormat = format.GetFormat($"\"{currencySymbol}\"#,##0{(exportFormat.DecimalDigit > 0 ? "." : "")}{decimalDigit}{(exportFormat.FormatType == "Percent" ? "%" : "")}");
                    else
                        cellStyle.DataFormat = format.GetFormat($"\"{currencySymbol}\"#0{(exportFormat.DecimalDigit > 0 ? "." : "")}{decimalDigit}{(exportFormat.FormatType == "Percent" ? "%" : "")}");
                    break;
                case "Discount":
                    double discount;
                    double.TryParse(val, out discount);
                    switch (exportFormat.DiscountFixedRule)
                    {
                        case "2":
                            discount = Math.Truncate(discount * 10) / 10;
                            break;
                        default:
                            discount = Math.Round(discount, 1);
                            break;
                    }
                    switch (cultureInfo.Name)
                    {
                        case "zh-CN":
                        case "zh-TW":
                            newCell.SetCellValue(discount.ToString("F1") + "折");
                            break;
                        default:
                            newCell.SetCellValue(Math.Round(100.0 - discount * 10.0) + "% off");
                            break;

                    }
                    break;
            }

            newCell.CellStyle = cellStyle;
        }
        /// <summary>
        /// 根据类型导出到Excel
        /// </summary>
        public void SetProperty(ExportDef exportDef, Region region, ICell newCell, string val, ICellStyle cellStyle, IDataFormat format)
        {
            switch (exportDef.DataType)
            {
                case "String": //字符串类型
                case "TimeSpan": //字符串类型
                    if (Encoding.Default.GetBytes(val).Length > 10000)
                    {
                        newCell.SetCellValue($"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Excel_400909426", "字段超长")}");
                    }
                    else
                    {
                        newCell.SetCellValue(val);
                        if (val.Contains("\n"))//支持自动换行
                        {
                            cellStyle.WrapText = true; // 设置自动换行  
                            newCell.CellStyle = cellStyle;
                        }
                    }
                    break;
                case "Timestamp":
                case "DateTime": //日期类型
                case "Time":
                case "Date":
                    if (DateTime.TryParse(val, out DateTime dateTime))
                    {
                        switch (exportDef.DataType)
                        {
                            case "Time":
                                newCell.SetCellValue(dateTime.ToString(region.TimeFormat));
                                break;
                            case "Date":
                                cellStyle.DataFormat = format.GetFormat(region.DateFormat);
                                newCell.SetCellValue(dateTime);
                                newCell.CellStyle = cellStyle;
                                break;
                            default:
                                cellStyle.DataFormat = format.GetFormat(region.DateTimeFormat);
                                newCell.SetCellValue(dateTime);
                                newCell.CellStyle = cellStyle;
                                break;
                        }
                    }
                    else
                    {
                        newCell.SetCellValue(val);
                    }
                    break;
                case "Boolean": //布尔型
                    if (bool.TryParse(val, out bool result))
                        newCell.SetCellValue(result);
                    else
                    {
                        newCell.SetCellValue(val.ToLower());
                    }
                    break;
                case "Int":
                case "Int16": //整型
                case "Int32":
                case "Int64":
                case "Byte":
                case "Long":
                    if (long.TryParse(val, out long intRes))
                        newCell.SetCellValue(intRes);
                    else
                    {
                        newCell.SetCellValue(val);
                    }
                    break;
                case "Decimal": //浮点型
                case "Double":
                    if (double.TryParse(val, out double doubleRes))
                        newCell.SetCellValue(doubleRes);
                    else
                    {
                        newCell.SetCellValue(val);
                    }
                    break;
                case "DBNull": //空值处理
                    newCell.SetCellValue("");
                    break;
                default:
                    newCell.SetCellValue(val);
                    break;
            }
        }
    }
}